package com.zsck.zsgy.ui.main.fragment

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.youth.banner.indicator.CircleIndicator
import com.zsck.commonbase.util.setNoRepeatClick
import com.zsck.zsgy.R
import com.zsck.zsgy.base.BaseFragment
import com.zsck.zsgy.databinding.FragmentHomeBinding
import com.zsck.zsgy.ui.main.adapter.HomeCirvcleAdapter
import com.zsck.zsgy.ui.main.adapter.HomeHotAdapter
import com.zsck.zsgy.ui.main.adapter.SurroundingApartmentAdapter
import com.zsck.zsgy.ui.main.fragment.home.HomeViewModel
import com.zsck.zsgy.ui.main.fragment.home.adapter.MyBannerAdapter
import com.zsck.zsgy.ui.main.bean.CityModel
import com.zsck.zsgy.ui.main.bean.CoverFile
import com.zsck.zsgy.ui.main.bean.HomeBean
import com.zsck.zsgy.util.Constants
import com.zsck.zsgy.util.Constants.Companion.CITY_ID
import com.zsck.zsgy.util.GlideUtils
import com.zsck.zsgy.util.PrefserHelper


class HomeFragment : BaseFragment<HomeViewModel, FragmentHomeBinding>() {

    companion object {
        fun newInstance() = HomeFragment()
    }

    private var hotAdapter = HomeHotAdapter()

    private var surroundingApartmentAdapter = SurroundingApartmentAdapter()

    private var homeCircleAdapter = HomeCirvcleAdapter()
    override fun initView(savedInstanceState: Bundle?) {
        binding.banner.setBannerGalleryEffect(0, 0, 0)

        binding.rcvHot.isNestedScrollingEnabled = false
        binding.rcvHot.layoutManager = LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false)
        binding.rcvHot.adapter = hotAdapter

        //item 点击事件
        hotAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var item = hotAdapter.getItem(position)
                ToastUtils.showShort("跳转：" + item.projectName)
            }
        })


        binding.rcvNearbyApartments.isNestedScrollingEnabled = false
        binding.rcvNearbyApartments.layoutManager = LinearLayoutManager(
            mContext,
            RecyclerView.HORIZONTAL,
            false
        )
        binding.rcvNearbyApartments.adapter = surroundingApartmentAdapter
        surroundingApartmentAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var item = surroundingApartmentAdapter.getItem(position)
                ToastUtils.showShort("跳转：" + item.projectName)
            }
        })

        binding.rcvSimpleCircle.isNestedScrollingEnabled = false
        binding.rcvSimpleCircle.layoutManager = GridLayoutManager(mContext, 2)
        binding.rcvSimpleCircle.adapter=homeCircleAdapter
        homeCircleAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var item = homeCircleAdapter.getItem(position)
                ToastUtils.showShort("跳转：" + item.contentCoverFile.fileId)
            }
        })



        binding.refreshLayout.setOnRefreshListener(OnRefreshListener {
            initData()
            binding.refreshLayout.finishRefresh(true)

        })
    }

    override fun layoutId(): Int {
        return R.layout.fragment_home
    }

    override fun lazyLoad() {


    }

    override fun initData() {
        binding.refreshLayout.autoRefresh()
        binding.homeViewModel = viewModel
        var cityName = ""
        if (PrefserHelper.getCurrentOrLastCityBean() != null) {
            cityName = PrefserHelper.getCurrentOrLastCityBean().city
        } else {
            cityName = "深圳"
        }

//        showDialog()
        viewModel.getCityByCityName(cityName)
        viewModel.cityModel.observe(this, Observer {
//            dismissDialog()
            loadHomeData(it, cityName)
            binding.refreshLayout.finishRefresh(true)
        })
        viewModel.errorLiveData.observe(this, Observer {
//            dismissDialog()
            binding.refreshLayout.finishRefresh(true)
        })

    }

    override fun onClick() {
        setNoRepeatClick(
            binding.tvEventMore, binding.tvHotType, binding.tvNearbyApartments,
            binding.tvSimpleCircle, binding.llSearch
        ) { it ->
            when (it) {
                binding.tvEventMore -> {
                    //跳转活动专区

                }
                binding.tvHotType -> {
                    //热门户型
                }
                binding.tvNearbyApartments -> {
                    //附近房源
                }
                binding.tvSimpleCircle -> {
                    //简单圈
                }
                binding.llSearch -> {
                    //搜索

                }

            }
        }

    }


    var cityId: String? = null
    private fun loadHomeData(cityModel: List<CityModel>?, cityName: String) {
        if (cityModel == null || cityModel.size == 0) {
            LogUtils.w("test", "cityModel is null")
            return
        }
        cityId = cityModel[0].id
        CITY_ID = (cityId as String?).toString()
//        showDialog()
        viewModel.getHomeData(
            CITY_ID,
            cityName,
            PrefserHelper.getCurrentOrLastCityBean()?.latitude.toString(),
            PrefserHelper.getCurrentOrLastCityBean()?.longitude.toString()
        )
        viewModel.homeModel.observe(this, Observer {
            setData(it)
//            dismissDialog()
            binding.refreshLayout.finishRefresh(true)
        })
        viewModel.errorLiveData.observe(this, Observer {
//            dismissDialog()
            binding.refreshLayout.finishRefresh(true)
        })
    }

    private fun setData(it: HomeBean?) {
        //banner
        setBanner(it)

        setActivi(it)
        hotAdapter.setList(it!!.hotHouse)
        surroundingApartmentAdapter.setList(it!!.surroundingApartments)
        homeCircleAdapter.setList(it!!.simpleCycle)

    }

    /**
     * 设置活动
     */
    private fun setActivi(it: HomeBean?) {
        val bigImage: List<HomeBean.MarketingActivity> =
            it?.getMarketingActivityBigImage() as List<HomeBean.MarketingActivity>
        val smallImage: List<HomeBean.MarketingActivity> =
            it?.getMarketingActivitySmallImage() as List<HomeBean.MarketingActivity>


        //设置活动标题
        if (bigImage != null && bigImage.size > 0) {
            binding.tvEventMore.setVisibility(View.VISIBLE)
            //            CoverFile coverFile = bigImage.get(0).getContentCoverFile();
            val coverFile: CoverFile? = bigImage[0].contentIndexBannerFile
            if (coverFile != null && coverFile.getFileId() != null) {
                GlideUtils.displayWithConnerDefault(
                    Constants.IMG_HOST + coverFile.getFileId(), binding.ivRecommendedAreaOne,
                    activity, 8, R.mipmap.recommended1
                )
            }
            val marketingActivity: HomeBean.MarketingActivity = bigImage[0]
            binding.oneTitle.setText(marketingActivity.getShareTitle())
            binding.oneSubTitle.setText(marketingActivity.getShareSubTitle())
            if (marketingActivity.getIsShowTitle()) {
                binding.oneTitle.setVisibility(View.VISIBLE)
                binding.oneSubTitle.setVisibility(View.VISIBLE)
            } else {
                binding.oneTitle.setVisibility(View.GONE)
                binding.oneSubTitle.setVisibility(View.GONE)
            }
        } else {
            binding.tvEventMore.setVisibility(View.GONE)
        }
        if (smallImage != null) {
            if (smallImage.size > 0 && smallImage[0] != null) {
                val coverFile: CoverFile? = smallImage[0].contentCoverFile
                if (coverFile != null && coverFile.getFileId() != null) {
                    GlideUtils.displayWithConnerDefault(
                        Constants.IMG_HOST + coverFile.getFileId(), binding.ivRecommendedAreaTwo,
                        activity, 8, R.mipmap.recommended2
                    )
                }
                val marketingActivity: HomeBean.MarketingActivity = smallImage[0]
                binding.twoTitle.setText(marketingActivity.getShareTitle())
                binding.twoSubTitle.setText(marketingActivity.getShareSubTitle())
                if (marketingActivity.getIsShowTitle()) {
                    binding.twoTitle.setVisibility(View.VISIBLE)
                    binding.twoSubTitle.setVisibility(View.VISIBLE)
                } else {
                    binding.twoTitle.setVisibility(View.GONE)
                    binding.twoSubTitle.setVisibility(View.GONE)
                }
            }
            if (smallImage.size > 1 && smallImage[1] != null) {
                val coverFile: CoverFile? = smallImage[1].contentCoverFile
                if (coverFile != null && coverFile.getFileId() != null) {
                    GlideUtils.displayWithConnerDefault(
                        Constants.IMG_HOST + coverFile.getFileId(),
                        binding.ivRecommendedAreaThree,
                        activity,
                        8,
                        R.mipmap.recommended3
                    )
                }
                val marketingActivity: HomeBean.MarketingActivity = smallImage[1]
                binding.threeTitle.setText(marketingActivity.getShareTitle())
                binding.threeSubTitle.setText(marketingActivity.getShareSubTitle())
                if (marketingActivity.getIsShowTitle()) {
                    binding.threeTitle.setVisibility(View.VISIBLE)
                    binding.threeSubTitle.setVisibility(View.VISIBLE)
                } else {
                    binding.threeTitle.setVisibility(View.GONE)
                    binding.threeSubTitle.setVisibility(View.GONE)
                }
            }
        }
    }

    /**
     * 设置banner数据
     */
    private fun setBanner(it: HomeBean?) {
        var bannerAdapter: MyBannerAdapter? = MyBannerAdapter(it?.banner, mContext)
        binding.banner.addBannerLifecycleObserver(this)
            .setAdapter(bannerAdapter)
            .setIndicator(CircleIndicator(mActivity))
            .setOnBannerListener { data, position ->
                var banner = data as HomeBean.BannerBean
                if (banner.detailType != null && banner.isVoidDetail != null) {
                    var fileId = banner.contentCoverFile.fileId
                    var imageUrl = Constants.IMG_HOST + fileId
                    //跳转网页
                }
            }
    }


}